$(function () {
    var start = {
        elem: '#startDate',
        format: 'YYYY-MM-DD hh:mm:ss',
        istime: true,
        choose: function (datas) {
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };
    var end = {
        elem: '#endDate',
        format: 'YYYY-MM-DD hh:mm:ss',
        istime: true,
        choose: function (datas) {
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(end);
    selectUserCommon();
    queryAjaxCouponList(1);
    $('body').on('click', '#submitFrom,#querySubmit', function () {
        //点击搜索查询从第一页开始查询
        queryAjaxCouponList(1);
    }).on('click','.coupon-shop-data',function () {
        var _this = $(this);
        var couponId = _this.data('id');
        $.ajax({
            url: baseloaction +'/admin/op/coupon/showCouponShopData',
            type:"post",
            data:{
                'couponId':couponId
            },
            success:function (result) {
                if(result.success==true){
                    var list = result.entity;
                    if(list==null || list.length ==0){
                        icModale(0,'优惠券没有设置使用范围');
                    }else{
                        var context = '';
                        $.each(list,function (index,shopData) {
                            context +='<div class="m-t m-b"><div class="m-r m-l">'+(index+1)+'、';
                            if(shopData.shopType=='COURSE'){
                                context +=shopData.shop.shopName +'【课程】'
                            }else if(shopData.shopType=='EXAM'){
                                context +=shopData.shop.shopName +'【试卷】'
                            }else if(shopData.shopType=='BOOK'){
                                context +=shopData.shop.shopName +'【图书】'
                            }else if(shopData.shopType=='MEMBER'){
                                context +=shopData.shop.shopName +'【会员】'
                            }else if(shopData.shopType=='QA'){
                                context +='限问答使用'
                            }else if(shopData.shopType=='ATTEND'){
                                context +='限旁听使用'
                            }
                            context +='</div></div>';
                        });
                        parent.layer.closeAll();
                        parent.layer.open({
                            type: 1,
                            area: ['620px', '520px'],
                            skin: 'layui-layer-demo',
                            title: '查看优惠券使用范围',
                            content:context ,
                            btn: '关闭',
                            yes: function (index, layero) {
                                parent.layer.close(index)
                            }
                        });
                    }
                }else{
                    icModale(0,result.message);
                }
            },
            error:function (error) {
                icModale(0,'系统错误，查看失败');
            }
        });
    });

    $('body').on("click", "#unlockBatch", function () { //批量停止
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            updateCouponStatusByIds(couponIds, obj, 2);
        }
    }).on('click', '.unlockAndHistory', function () {//单个停止或单个恢复
        var couponIds = $(this).data('id');
        var status = $(this).attr('data-status');
        var obj = $(this);
        if (status == 1) {
            updateCouponStatusByIds(couponIds, obj, 1);
        }
        if (status == 2) {
            updateCouponStatusByIds(couponIds, obj, 2);
        }
    }).on("click", "#historyBatch", function () { //批量恢复
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            updateCouponStatusByIds(couponIds, obj, 1);
        }
    }).on("click", "#deleteBatch", function () {//批量删除
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            icModale(2, "删除后不可恢复，仍然确认删除么？", 3, function () {
                updateCouponStatusByIds(couponIds, obj, 3);
            });
        }
    }).on('click', '.deleteCoupon', function () {//单个删除
        var couponIds = $(this).data('id');
        var obj = $(this);
        icModale(2, "删除后不可恢复，仍然确认删除么？", 3, function () {
            updateCouponStatusByIds(couponIds, obj, 3);
        });
    });

    //判断勾选ID是否为空
    function obtainIds(obj) {
        if (obj.size() == 0) {
            icModale(0, "请选择要批量操作的数据");
            return null;
        } else {
            var couponIds = "";
            obj.each(function (index, em) {
                couponIds += em.value + ",";
            });
            couponIds = couponIds.substr(0, couponIds.length - 1);
            return couponIds;
        }
    }
});

/**
 * 获取优惠券列表页面
 * @param pageNo 当前页码
 */
function queryAjaxCouponList(pageNo) {
    var params = $("#search-form").serializeJSON();
    var other = $("input[name='other']").val();
    if (other == 1){
        params.conditions=7;
    }
    params = JSON.stringify(params);
    var obj = {
        url: baseloaction + '/admin/op/coupon/queryOpCouponListPage',//请求URL
        contextId: 'coupon-list-context',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: queryAjaxCouponList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        selectAllId: 'select-all-coupon', //全选框ID
        callback: function () {//数据加载完成回调
            $("#totalNum").html("（共"+total+"个优惠券）");
            $("#couponCount").val(total);
        }
    };
    ajaxGetListData(obj)
}


/**
 * 批量封禁，批量恢复，批量删除
 * @param userIds
 * @param obj
 * @param isavalible
 */
function updateCouponStatusByIds(couponIds, obj, status) {
    $.ajax({
        url: baseloaction + "/admin/op/coupon/updateOpCouponStatus",
        data: {"couponIds":couponIds,"status": status},
        type: "post",
        dataType: "json",
        success: function (result) {
            if (result.success) {
                icModale(0, result.message);
                var couponList = result.entity;
                if(couponList !=null && couponList.length > 0){
                    if(status==3){//删除
                        var couponCount = $("#couponCount").val();
                        var count = couponCount - couponList.length;
                        $("#totalNum").html('（共' + count + '张优惠券）');
                        if (count == 0) {
                            $("#tbodyCoupon").append(
                                ' <td colspan="11" class="text-center">'
                                + '<div class="noDataTipsBox">'
                                + '<p><span class="c-4e fs16">亲，还没有数据~~~</span></p>'
                                + '</div>'
                                + '</td>'
                            );
                        }
                            console.log(obj);
                            $.each(obj,function (index,coupon) {
                                $(coupon).parents("tr").remove();
                            });




                    }else{
                        $.each(couponList,function (index,coupon) {//处理页面显示
                            var context = '';
                            if(coupon.status ==1){
                                context = '<span class="label label-info">进行中</span>';
                            }else if(coupon.status ==0){
                                context = '<span class="label label-info">未开始</span>';
                            }else if(coupon.status ==2){
                                context = '<span class="label label-danger">已停止</span>';
                            }else if(coupon.status ==7){
                                context = '<span class="label label-danger">已结束</span>';
                            }
                            $("#coupon-status-"+coupon.id).html(context);

                            if(status ==2){//停止
                                //如果是停止状态，则把赠送按钮删除
                                $("#selectUser_"+coupon.id).remove();
                                var em = $("#unlockAndHistory_"+coupon.id);
                                em.html('<i class="fa fa-history"></i>');
                                em.data('original-title','恢复');
                                em.attr("data-original-title",'恢复');
                                em.data('status',1);
                                em.attr("data-status",'1');
                            }else if(status ==1){
                                var em = $("#unlockAndHistory_"+coupon.id);
                                em.html('<i class="fa fa-pause"></i>');
                                em.data('original-title','停止');
                                em.attr("data-original-title",'停止');
                                em.data('status',2);
                                em.attr("data-status",'2');
                                var _list = $("#selectUser_"+coupon.id);
                                if(_list ==null || _list.length <=0){
                                    var context = '<a id="selectUser_'+coupon.id+'" data-id="'+coupon.id+'" data-original-title="赠送" data-placement="bottom" data-toggle="tooltip" class="c-master fs14 ml5 selectUser" href="javascript:void (0);"><i class="fa fa-gift"></i></a>';
                                    em.after(context);
                                }
                            }
                        });
                    }
                }

                /*
                if (2 == status) {
                    var availableCount = $("#availableCount").val();
                    $("#availableCount").val((availableCount - obj.size()));
                    obj.parents('tr').find('.status').html('');
                    obj.parents('tr').find('.status').append('<span class="label label-danger">已停止</span>');
                    obj.parents('tr').find(".unlockAndHistory").html("");
                    obj.parents('tr').find(".unlockAndHistory").data('status', '2');
                    obj.parents('tr').find(".unlockAndHistory").append('<i class="fa fa-history"></i>');
                    obj.parents('tr').find(".unlockAndHistory").attr('data-original-title', "恢复")
                }
                if (1 == status) {
                    var availableCount = $("#availableCount").val();
                    $("#availableCount").val((availableCount + obj.size()));
                    obj.parents('tr').find('.status').html('');
                    obj.parents('tr').find('.status').append('<span class="label label-info">进行中</span>');
                    obj.parents('tr').find(".unlockAndHistory").html("");
                    obj.parents('tr').find(".unlockAndHistory").data('status', '1');
                    obj.parents('tr').find(".unlockAndHistory").append('<i class="fa fa-pause"></i>');
                    obj.parents('tr').find(".unlockAndHistory").attr('data-original-title', "停止")
                }
                */
            } else {
                icModale(0, result.message);
            }
        },
        error: function (error) {
            icModale(0, "系统繁忙,请稍后重试");
        }
    })
}

/**
 * 查找用户赠送
 */
var dataId="";
function selectUserCommon() {
    $('body').on('click', '.selectUser', function () {
        selectUser("checkbox","");
        dataId = $(this).data('id');
    })
}

/**
 * 选择课程回调
 * @param result 回调数据
 */
function selectUserCallback(result) {
    if(result!=null && result.length>0){
        var userIds = "";
        $.each(result,function (index,user) {
            if(userIds.indexOf(","+user.id+",")==-1 && userIds.indexOf(user.id + ",") == -1){
                userIds +=user.id+","
            }
        });
        $.ajax({
            url: baseloaction + "/admin/op/coupon/presentOpCoupon",
            data: {"userIds": userIds, "couponId": dataId},
            dataType: "json",
            type: "post",
            success: function (result) {
                if(result.success){
                    icModale(0, result.message);
                    dataId="";
                    parent.layer.close(index);
                }else{
                    icModale(0, result.message);
                }
            }
        });
    }
}

